package com.elf.bluetoothtest.adapter;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.elf.bluetoothtest.entity.BluetoothDeviceDetail;
import com.elf.bluetoothtest.widget.BluetoothListItemWidget;

public class BluetoothListAdapter extends ArrayAdapter<BluetoothDeviceDetail> {

    public BluetoothListAdapter(@NonNull Context context) {
        super(context, 0);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            convertView = new BluetoothListItemWidget(getContext());
        }

        BluetoothDeviceDetail deviceDetail = getItem(position);
        ((BluetoothListItemWidget) convertView).setData(deviceDetail.device, deviceDetail.rssi);

        return convertView;
    }

    @Override
    public void add(@Nullable BluetoothDeviceDetail object) {
        if (getCount() > 0) {
            for (int i = 0; i < getCount(); i++) {
                BluetoothDeviceDetail detail = getItem(i);
                if (detail.device != null) {
                    if (equals(detail.device.getName(), object.device.getName())
                            && equals(detail.device.getAddress(), object.device.getAddress())) {
                        detail.rssi = object.rssi;
                        notifyDataSetChanged();
                        return;
                    }
                }
            }
        }
        super.add(object);
    }

    private boolean equals(String s1,String s2) {
        if (s1 == null && s2 == null) {
            return true;
        }

        if (s1 != null) {
            return s1.equals(s2);
        }
        if (s2 != null) {
            return s2.equals(s1);
        }
        return false;
    }
}
